<template>
    <div class="app-detail">
        <list-layout>
            <!--search condition-->
            <div slot="search">
                <el-form :model="queryParams" :inline="true" ref="queryForm" v-show="showSearch" label-width="128px">
                    <!-- <el-form-item :label="$t('mrbForm.materialName')">
                        <el-input v-model="queryParams.materialName"
                            :placeholder="$t('public.placeholder', { placeholder: $t('mrbForm.materialName') })" clearable
                            size="small" @keyup.enter.native="handleQuery" />
                    </el-form-item> -->
                    <el-form-item :label="$t('mrbForm.materialNo')">
                        <el-input v-model="queryParams.materialCode"
                            :placeholder="$t('public.placeholder', { placeholder: $t('mrbForm.materialNo') })" clearable
                            size="small" @keyup.enter.native="handleQuery" />
                    </el-form-item>
                    <el-form-item :label="$t('inspectionManagement.inspectNo')">
                        <el-input v-model="queryParams.inspectionOrder"
                            :placeholder="$t('public.placeholder', { placeholder: $t('inspectionManagement.inspectNo') })"
                            clearable size="small" @keyup.enter.native="handleQuery" />
                    </el-form-item>
                    <el-form-item :label="$t('public.status')">
                        <el-select size="small" v-model="queryParams.status" clearable>
                            <el-option v-for="(item, index) in satusOptions" :key="item.Value" :value="item.Value"
                                :label="item.Label"></el-option>
                        </el-select>
                    </el-form-item>


                </el-form>
                <div style="display: flex; justify-content: center">
                    <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">{{ $t("public.search")
                    }}</el-button>
                    <el-button icon="el-icon-refresh" class="resectBtn" size="mini" @click="resetQuery">{{
                        $t("public.reset") }}</el-button>
                </div>
            </div>

            <div class="app-container">
                <div class="container-header">
                    <!--审批-->
                    <el-button size="mini" @click="showApproval" style="margin-bottom: 10px;" v-hasPermi="['ny-iqc:trialinvestment:Approve']">
                        {{ $t('home.approve') }}
                    </el-button>
                    <!--撤销-->
                    <el-button size="mini" @click="handleRevoke" style="margin-bottom: 10px;" v-hasPermi="['ny-iqc:trialinvestment:Approve']">
                        {{ $t('home.revoke') }}
                    </el-button>
                    <!--撤销-->
                    <el-button size="mini" @click="handleMes" style="margin-bottom: 10px;" v-hasPermi="['ny-iqc:trialinvestment:Approve']">
                        向MES发起试投
                    </el-button>
                </div>
                <!--试投清单 表格数据-->
                <div class="container-table">
                    <el-table class="table-fixed" ref="multipleTable" :key="incomingKey" v-loading="loading"
                        :height="tableHeight" border :data="producingTrialItems" @selection-change="handleSelectionChange">

                        <el-table-column type="selection" width="55" fixed="left" align="center"
                            :show-overflow-tooltip="true" />
                        <!--检验单号-->
                        <el-table-column :label="$t('outlier.order')" sortable align="left" prop="inspectionOrder"
                            min-width="120" :show-overflow-tooltip="true" />
                        <!--检验批号-->
                        <el-table-column :label="$t('inspectionManagement.InspectBatchNo')" sortable align="left" prop="inspectionLotMark"
                            min-width="120" :show-overflow-tooltip="true" />
                        <!--批次号-->
                        <el-table-column :label="$t('inspectionManagement.lot')" sortable align="left" prop="lot"
                            min-width="120" :show-overflow-tooltip="true" />

                        <!--所在厂区-->
                        <el-table-column :label="$t('inspectionManagement.factory')" sortable align="left"
                            prop="factoryName" min-width="120" :show-overflow-tooltip="true" />

                        <!--物料编码-->
                        <el-table-column :label="$t('material.materialCode')" sortable align="left" prop="materialCode"
                            min-width="100" :show-overflow-tooltip="true" />
                        <!--物料描述-->
                        <el-table-column :label="$t('mrbForm.materialName')" sortable align="left" prop="materialName"
                            min-width="120" :show-overflow-tooltip="true" />
                        <!--供应商名称-->
                        <el-table-column :label="$t('mrbForm.supplierName')" sortable align="left" prop="supplierName"
                            min-width="120" :show-overflow-tooltip="true" />
                        <!--批数量-->
                        <el-table-column :label="$t('inventoryManagement.batchQuantity')" sortable align="left" prop="batchAmount"
                            min-width="120" :show-overflow-tooltip="true" />
                        <!--到货日期-->
                        <el-table-column :label="$t('inventoryManagement.arrivalTime')" sortable align="left" prop="cputime"
                            min-width="95" :show-overflow-tooltip="true" />
                        <!--报检日期-->
                        <el-table-column :label="$t('inspectionManagement.deliveryDate')" sortable align="left"
                            prop="deliveryDate" min-width="95" :show-overflow-tooltip="true" />

                        <!--检验结果-->
                        <el-table-column :label="$t('inspectionManagement.checkoutResult')" sortable align="left"
                            prop="decideResult" min-width="95" :show-overflow-tooltip="true">

                            <!-- <template slot-scope="scope">
                                <span v-if="scope.row.decideResult == '1'">{{ $t('defectIncoming.qualified')
                                }}</span>
                                <span v-if="scope.row.decideResult == '0'">{{ $t('defectIncoming.unqualified') }}</span>

                            </template> -->
                        </el-table-column>
                        <!--一次试投结果-->
                        <el-table-column :label="$t('trialinvestment.oneResults')" sortable align="left"
                            prop="oneTrialResult" min-width="120" :show-overflow-tooltip="true">
                            <!-- <template slot-scope="scope">

                                <span v-if="scope.row.oneTrialResult == '1'">{{ $t('defectIncoming.qualified')
                                }}</span>
                                <span v-if="scope.row.oneTrialResult == '0'">{{ $t('defectIncoming.unqualified') }}</span>

                            </template> -->
                        </el-table-column>

                        <!--二次试投结果-->
                        <el-table-column :label="$t('trialinvestment.Secondresults')" sortable align="left"
                            prop="twoTrialResult" min-width="120" :show-overflow-tooltip="true">
                            <!-- <template slot-scope="scope">

                                <span v-if="scope.row.twoTrialResult == '1'">{{ $t('defectIncoming.qualified')
                                }}</span>
                                <span v-if="scope.row.twoTrialResult == '0'">{{ $t('defectIncoming.unqualified') }}</span>

                            </template> -->
                        </el-table-column>

                        <!--试投文件-->
                        <el-table-column :label="$t('trialinvestment.trialProduceResultFile')" sortable align="left"
                            prop="twoTrialResult" min-width="95" :show-overflow-tooltip="true">
                            <template slot-scope="scope">
                                <a v-if="scope.row.status > 1" @click="showFileList(scope.row)">查阅</a>
                            </template>
                        </el-table-column>

                        <!--试投平台-->
                        <el-table-column :label="'试投平台'" align="left" prop="platform" min-width="95" :show-overflow-tooltip="true">
                            <template slot-scope="scope">
                                <div>
                                    <span>{{ scope.row.isMes == 1 ? 'MES' : 'GQMS' }}</span>
                                </div>
                            </template>
                        </el-table-column>

                        <!--状态-->
                        <el-table-column :label="$t('public.status')" sortable align="left" prop="statusName"
                            min-width="120" :show-overflow-tooltip="true">
                            <!-- <template slot-scope="scope">
                            <span v-if="scope.row.twoTrialResult=='1'">合格</span>
                            <span v-if="scope.row.twoTrialResult=='0'">不合格</span>
                        </template> -->
                        </el-table-column>
                        <!--操作-->
                        <el-table-column :label="$t('public.opera')" fixed="right" align="center" width="140">
                            <template slot-scope="scope">
                                <div class="action-wrap" v-if="scope.row.isMes == 1">
                                    <el-button type="primary" @click="handelpullMesData(scope.row)" round size="small" v-if="scope.row.status == 1">获取一次试投数据</el-button>
                                    <el-button type="primary" @click="handelpullMesData(scope.row)" round size="small" v-if="scope.row.status == 2">重新获取一次试投数据</el-button>
                                    <el-button type="primary" @click="handelpullMesData(scope.row)" round size="small" v-if="scope.row.status == 5">获取二次试投数据</el-button>
                                    <el-button type="primary" @click="handelpullMesData(scope.row)" round size="small" v-if="scope.row.status == 6">重新获取二次试投数据</el-button>
                                </div>
                                <div class="action-wrap" v-else>
                                    <!--待上传-->
                                    <file-upload :isShowTip="false" :singleUplaod="true" :showFileList="false" v-if="scope.row.status == 1"
                                        @change="list => fileChange(list, scope.row.id)"
                                        :uploadButtonText="$t('trialinvestment.toUpload1stTrial')"></file-upload>
                                    <!--重新上传一次试投，2 一次待审批-->
                                    <file-upload :isShowTip="false" :singleUplaod="true"  :showFileList="false" v-if="scope.row.status == 2"
                                        @change="list => fileChange(list, scope.row.id)"
                                        :uploadButtonText="$t('trialinvestment.toReUpload1stTrial')"></file-upload>

                                    <!--二次待上传-->
                                    <file-upload :isShowTip="false" :singleUplaod="true"  :showFileList="false" v-if="scope.row.status == 5"
                                        @change="list => fileChange(list, scope.row.id)"
                                        :uploadButtonText="$t('trialinvestment.toUpload2ndTrial')"></file-upload>

                                    <!--重新上传二次试投-->
                                    <file-upload :isShowTip="false" :singleUplaod="true"  :showFileList="false" v-if="scope.row.status == 6"
                                        @change="list => fileChange(list, scope.row.id)"
                                        :uploadButtonText="$t('trialinvestment.toReUpload2ndTrial')"></file-upload>
                                    <!-- <el-button size="small">{{
                                        $t('trialinvestment.toUpload1stTrial') }}</el-button>
                                    <el-button v-if="scope.row.status == '5'" size="small">{{
                                        $t('trialinvestment.toUpload2ndTrial') }}</el-button> -->
                                </div>
                            </template>
                        </el-table-column>
                        <!-- <el-table-column :label="$t('mrbForm.supplierBatchNo')" sortable  align="left" prop="lichn" min-width="120" :show-overflow-tooltip="true" /> -->

                    </el-table>

                    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
                        :limit.sync="queryParams.pageSize" @pagination="getList"
                        layout="total, sizes, prev, pager, next, jumper" />
                </div>

            </div>
        </list-layout>

        <!--approval modal-->

        <el-dialog :title="$t('inventoryManagement.approval')" :visible="showApprovalModal" center top="11vh" width="600px"
            @close="close">
            <el-form :model="approvalModel" size="small" label-suffix=":" ref="typeModel" label-width="108px">
                <el-row>
                    <el-col :span="24">
                        <el-form-item v-bind:label="$t('trialinvestment.viewAttachment')" style="width:100%">
                            <!-- <file-upload :limit="1" bizType="onceTrialDoc" :otherList="onceTrialDocFile" :bizId="typeModel.inspectionId"
                             disabled   v-model="typeModel.onceTrialDoc" @change="(fileList)=>picChange(fileList,'onceTrialDoc')"></file-upload> -->
                            <a class="download-item" :href="apporvalFileInfo.url">{{ apporvalFileInfo.fileName }}</a>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="24" class="dia">

                    <el-col :span="24">
                        <el-form-item
                            :label="approvalModel.isSecond ? $t('trialinvestment.Secondary') : $t('trialinvestment.Onceary')"
                            prop="approvalModel.result">
                            <el-radio-group v-model="approvalModel.result" class="smallRadio">
                                <el-radio :label="1"> {{ $t('inventoryManagement.pass') }} </el-radio>
                                <el-radio :label="0"> {{ $t('inventoryManagement.fail') }} </el-radio>

                            </el-radio-group>
                        </el-form-item>
                    </el-col>

                </el-row>
                <el-row v-if="approvalModel.result == 0 && !approvalModel.isSecond">
                    <el-col :span="24">
                        <el-form-item :label="$t('trialinvestment.ifTwiceTryProduce')" prop="approvalModel.secondTrial">
                            <el-radio-group v-model="approvalModel.secondTrial" class="smallRadio">
                                <el-radio :label="1"> {{ $t('public.yes') }} </el-radio>
                                <el-radio :label="0"> {{ $t('public.no') }} </el-radio>

                            </el-radio-group>
                        </el-form-item>
                    </el-col>

                </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="close" icon="el-icon-document" size="small">{{ $t('public.cancel') }}
                </el-button>
                <el-button type="primary" @click="submitApproval" icon="el-icon-document" size="small">{{ $t('public.save')
                }}
                </el-button>
            </div>
        </el-dialog>

        <!--view files of producing trial-->
        <el-dialog :visible="showFilesModal" center top="11vh" width="600px" @close="close">
            <el-form :model="approvalModel" size="small" label-suffix=":" ref="typeModel" label-width="108px">
                <el-row v-if=" currentFiles.one != undefined">
                    <el-col :span="24">
                        <el-form-item v-bind:label="$t('trialinvestment.file1st')" style="width:100%">
                            <a class="download-item" :href="currentFiles.one.url">{{ currentFiles.one.fileName }}</a>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row v-if=" currentFiles.two != undefined">
                    <el-col :span="24">
                        <el-form-item v-bind:label="$t('trialinvestment.file2nd')" style="width:100%">
                            <a class="download-item" :href="currentFiles.two.url">{{ currentFiles.two.fileName }}</a>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="close" icon="el-icon-document" size="small">{{ $t('public.close') }}
                </el-button>
            </div>
        </el-dialog>

        <el-dialog :visible="showMesModal" center top="11vh" width="600px" @close="showMesModal = false,$refs['MesModel'].resetFields()">
            <el-form :model="MesFormData" size="small" label-suffix=":" ref="MesModel" :rules="mesRules" label-width="108px">
                <el-row>
                    <el-col :span="24">
                        <el-form-item :label="'是否拉力'" prop="isPull">
                            <el-select size="small" v-model="MesFormData.isPull" clearable>
                                <el-option v-for="(item, i) in pullObj" :key="item.value" :value="item.value"
                                    :label="item.label"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item :label="'浆料类型'" prop="slurryType">
                            <el-select size="small" v-model="MesFormData.slurryType" clearable>
                                <el-option v-for="(item, i) in dict.type.MES_TRIAL_INVESTMENT_SLURRY_TYPE" :key="item.value" :value="item.value"
                                    :label="item.label"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item :label="'试投批号'" prop="trialInvestmentNo">
                            <el-input v-model="MesFormData.trialInvestmentNo"
                            :placeholder="$t('public.placeholder', { placeholder: '试投批号' })" clearable
                            size="small" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item :label="'试投数量'" prop="trialInvestmentCount">
                            <el-input type="number" v-model="MesFormData.trialInvestmentCount"
                            :placeholder="$t('public.placeholder', { placeholder: '试投数量' })" clearable
                            size="small" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="showMesModal = false,$refs['MesModel'].resetFields()" icon="el-icon-close" size="small">{{ $t('public.close') }}
                </el-button>
                <el-button type="primary" @click="handelMesConfirm" icon="el-icon-document" size="small">{{ $t('public.save') }}
                </el-button>
            </div>
        </el-dialog>



        <import-dialog :visible.sync="showImportModal" :showDownload="false" @callback="uploadCallback"
            :action="'/ny-iqc/project/import'" :templateUrl="'/static/auditProject.xlsx'" />
    </div>
</template>
<script>

import { mapGetters, mapState } from 'vuex'
import OptionItem from './OptionItem'
import SelectUserDialog from '@/views/components/SelectUserDialog'
//import approvalDialog from './components/approvalDialog.vue'
import importDialog from '../../components/importDialog'
import { geFileByBiz } from '@/api/file/file'

import {
    // investmentlistAPI,
    investmentapproveAPI, isInitiateAPI,
    queryProducingTrail,
    approvalProducingTrail//approval trail item
    ,
    saveTrailFile,
    revokeTrialInvestAPI,
    pushToMes,
    pullMesData
} from "@/api/inventoryManagement/investment"
export default {
    components: {
        importDialog
    },
    dicts:['MES_TRIAL_INVESTMENT_SLURRY_TYPE'],
    data() {
        var checkNum = (rule, value, callback) => {
            if (!value) {
            return callback(new Error('请输入'));
            }
            console.log(value)
            if (value < 0 || String(value).indexOf('-') !== -1) {
            callback(new Error('请输入大于等于0数字值'));
            } else {
            callback();
            }
        };
        return {
            pullObj:[
                {label:'是',value:'1'},
                {label:'否',value:'0'}
            ],
            slurryTypeObj:[
            {label:'01-背银',value:1},
            {label:'02-铝浆',value:2},
            {label:'03-背面主栅',value:3},
            {label:'04-正面主栅',value:4},
            {label:'05-背面细栅',value:5},
            {label:'06-正面细栅',value:6},
            ],
            showMesModal:false,
            MesFormData:{
                isPull:'',
                slurryType:'',
                trialInvestmentNo:'',
                trialInvestmentCount:''
            },
            mesRules: {
                isPull: [{
                    required: true,
                    message: '请选择',

                }],
                slurryType: [{
                    required: true,
                    message: '请选择',

                }],
                trialInvestmentNo: [{
                    required: true,
                    message: '请输入',

                }],
                trialInvestmentCount: [
                    { required:true,validator: checkNum, trigger: 'blur' }
                ],
            },
            queryParams: {
                pageNum: 1,
                pageSize: 20
            },
            // 总条数
            total: 0,

            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            /**
             *
             */
            showFilesModal: false,//show window to view list of producing trial files
            satusOptions: [

                new OptionItem(1, "待上传"),
                new OptionItem(2, "一次试投待审批"),
                new OptionItem(3, "一次试投审批通过"),
                new OptionItem(4, "一次试投审批不通过"),
                new OptionItem(5, "待上传二次试投文件"),
                new OptionItem(6, "二次试投待审批"),
                new OptionItem(7, "二次试投审批通过"),
                new OptionItem(8, "二次试投审批不通过")
            ],
            showImportModal: false,
            // producing trail items which for rendering in the page table
            producingTrialItems: [],
            //show approval modal window
            showApprovalModal: false,
            //for approval
            approvalModel: {
                result: 0, //whether approvaled
                secondTrial: 1,
                isSecond: false
            },
            //files current view
            currentFiles: {
                one: undefined,
                two: undefined
            },
            //end
            showSearch: true,
            tableHeight: 'calc(100vh - 308px)',

            typeOpen: false,


            typeModel: {
                twiceTrial: '0'
            },
            twiceTrial: "1",
            onceTrialDocFile: [],
            twiceTrialDocFile: [],

            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            stemList: [],

            // 弹出层标题
            title: '',
            // 是否显示弹出层
            open: false,
            // 日期范围
            dateRange: [],
            selectRows: [],
            rowifInspect: '',
            // 查询参数

            // 表单参数
            form: {},
            // 表单校验
            rules: {
                onceTrialResult: [{
                    required: true,
                    message: '请选择试投结果',

                }],
                onceTrialDoc: [{
                    required: true,
                    message: '一次试投审批文件不能为空',
                }],
                onceTrialMaterials: [{
                    required: true,
                    message: '一次试投材料不能为空',

                }],
                twiceTrial: [{
                    required: true,
                    message: '是否二次试投',
                }],
                twiceTrialResult: [{
                    required: true,
                    message: '请选择二次试投结果',

                }],
                twiceTrialMaterials: [{
                    required: true,
                    message: '二次试投材料不能为空',
                }],
                twiceTrialDoc: [{
                    required: true,
                    message: '二次试投审批文件不能为空'
                }],

            },
            fullscreen: false,
            incomingKey: 0,
            projectList: [],
            //抽样类型 1：正常，2：放宽，3：加严
            samplingTypeList: [
                { value: "1", label: "正常" },
                { value: "2", label: "放宽" },
                { value: "3", label: "加严" },
            ],
            //触发方式（1：自动触发，2：手动触发）
            triggerModeList: [
                { value: "1", label: "自动触发" },
                { value: "2", label: "手动触发" }
            ],

            ruleData: {},   // 规则详情
            fileList: [],
            disabled: false,
            typeOpen2: false,
            typeOpen3: false,
            twotype: ""
        }
    },
    mounted() {
        this.getList()
    },
    activated() {

        this.getList()
    },
    filters: {
        timefilter(time) {
            if (!time) {
                return ""
            }
            var date = new Date(time);
            var Y = date.getFullYear() + '-';
            var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
            var D = date.getDate() + ' ';
            var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
            var m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
            var s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();

            return Y + M + D + h + m + s
        }
    },
    computed: {
        ...mapGetters(['userId', 'name', 'deptName']),

        apporvalFileInfo: {
            get() {
                if (this.selectRows.length == 1) {
                    const item = this.selectRows[0];
                    let url = '';
                    let fileName = '';
                    switch (item.status) {
                        case 2: url = item.oneTrialFileUrl; break;
                        case 6: url = item.twoTrialFileUrl; break;
                    }
                    if (url) {
                        const index = url.lastIndexOf('/');
                        fileName = url.substr(index + 1);
                    }
                    return {
                        url,
                        fileName
                    };
                }
                return {};
            }
        }

    },

    methods: {
        /*
        INVESTMENT_STATUS_ONE(1,"待上传"),
        INVESTMENT_STATUS_TWO(2,"一次试投待审批"),
        INVESTMENT_STATUS_THREE(3,"一次试投审批通过"),
        INVESTMENT_STATUS_FOUR(4,"一次试投审批不通过"),
        INVESTMENT_STATUS_FIVE(5,"待上传二次试投文件"),
        INVESTMENT_STATUS_SIX(6,"二次试投待审批"),
        INVESTMENT_STATUS_SEVEN(7,"二次试投审批通过"),
        INVESTMENT_STATUS_EIGHT(8,"二次试投审批不通过"),
        */
        handelpullMesData(row){
            pullMesData(row.id).then(res => {
                if(res.code == 200){
                    this.$modal.msgSuccess(res.msg)
                    this.getList()
                }else{
                    this.$modal.msgError(res.msg);
                }
            })
        },
        handelMesConfirm(){
            this.$refs['MesModel'].validate((valid) => {
                if (valid) {
                    let temp = JSON.parse(JSON.stringify(this.MesFormData))
                        temp.id = this.ids[0]
                    pushToMes(temp).then(res => {
                        if(res.code == 200){
                            this.$modal.msgSuccess(res.msg)
                            this.showMesModal = false
                            this.$refs['MesModel'].resetFields()
                            this.getList()
                        }else{
                            this.$modal.msgError(res.msg);
                        }
                    })
                }else{

                }
            })
        },
        getFileName(url) {
            if (url) {
                const index = url.lastIndexOf('/');
                return url.substr(index + 1);
            }
            return '';
        },
        showFileList(row) {

            this.currentFiles.one = undefined;
            this.currentFiles.two = undefined;
            if (row.status > 1) {
                this.currentFiles.one = {
                    url: row.oneTrialFileUrl,
                    fileName: this.getFileName(row.oneTrialFileUrl)
                }
                this.currentFiles.one.fileName = this.getFileName(row.oneTrialFileUrl);

                if (row.status > 5) {
                    this.currentFiles.two = {
                        url: row.twoTrialFileUrl,
                        fileName: this.getFileName(row.twoTrialFileUrl)
                    }
                    // this.currentFiles.two.url = row.twoTrialFileUrl;
                    // this.currentFiles.two.fileName = this.getFileName(row.twoTrialFileUrl);
                }

                // if(!this.currentFiles.one&&!this.currentFiles.one.url&&!this.currentFiles.two.url){
                //         this.$modal.msgWarning(this.$t('trialinvestment.nofilesWarning'));
                // }
                // else
                {
                    this.showFilesModal = true;
                }
            }



        },
        fileChange(fileList, id) {

            console.log('file change.................', fileList);
            //save file url
            console.log(id);
            saveTrailFile({
                trialInvestmentId: id,
                fileUrl: fileList[0].url
            }).then(res => {
                if (res.code != 200) {
                    this.$modal.msgError(res.msg);
                    console.error(res.msg);
                }
                else {//reload  to refresh ui data
                    this.getList();
                }

            });
        },
        showImport() {
            this.showImportModal = true;
        },
        uploadCallback(rlt, res) {
            if (rlt) {

                console.log(res);
                //save file url
                // saveTrailFile({
                //     trialInvestmentId:this.ids[0],
                //     fileUrl:res.
                // });
            }

        },
        //approval
        submitApproval() {

            //
            this.$modal.confirm(this.$t('trialinvestment.confirmApproval')).then(() => {

                const data = {
                    trialInvestmentId: this.ids[0],
                    approveStatus: this.approvalModel.result,
                    hasTwo: this.approvalModel.secondTrial
                };
                console.log(data);
                approvalProducingTrail(data).then(res => {
                    //
                    if (res.code == 200) {
                        this.$modal.msgSuccess(this.$t('tips.approveSuccess'));
                        this.getList();
                        this.showApprovalModal = false;
                    }
                    else {
                        console.error(res.msg);
                        this.$modal.msgError(res.msg);
                    }
                    //
                });

            });
            //

        },
        handleMes() {
          if (this.ids.length !== 1) {
            this.$modal.msgWarning(
                this.$t('inspectionManagement.pleaseSelectOne')
            )
            return;
          }
          this.showMesModal = true
        },
        //handle of approval
        handleRevoke() {
          if (this.ids.length !== 1) {
            this.$modal.msgWarning(
                this.$t('inspectionManagement.pleaseSelectOne')
            )
            return;
          }
          this.$modal.confirm(this.$t('是否撤销试投?')).then(() => {
            revokeTrialInvestAPI(this.ids).then(res => {
              if (res.code == 200) {
                this.$modal.msgSuccess("撤销成功");
                this.getList();
              } else {
                this.$modal.msgError(res.msg);
              }
            });
          })
        },
        showApproval() {

            if (this.ids.length !== 1) {
                this.$modal.msgWarning(
                    this.$t('inspectionManagement.pleaseSelectOne')
                )
                return;
            }
            let item = this.selectRows[0];
            console.log(item);
            // let canApproval=true;
            switch (item.status) {
                case 2: this.approvalModel.isSecond = false; break;//一次试投待审批
                case 6: this.approvalModel.isSecond = true; break;//二次试投待审批
                default: this.$modal.msgWarning(this.$t('trialinvestment.approvalWaring') +
                    item.statusName + ',' + this.$t('trialinvestment.approvalWaringUpload'));
                    return;
            }
            console.log('approvalModel', this.approvalModel);
            this.showApprovalModal = true;
        },

        // 多选框选中数据
        handleSelectionChange(selection) {
            console.log(selection)
            this.selectRows = selection;
            this.ids = selection.map(item => item.id);
        },
        geFileByBizlist() {
            geFileByBiz({ bizId: this.typeModel.inspectionId }).then((res) => {
                let onceTrialDoc = []
                let onceTrialMaterials = []
                let twiceTrialDoc = []
                let twiceTrialMaterials = []
                res.data.forEach((io) => {
                    var index = io.originalFileName.lastIndexOf(".");
                    var ext = io.originalFileName.substr(index + 1);
                    if (io.bizType === 'onceTrialDoc') {
                        onceTrialDoc.push(io)
                        this.typeModel.onceTrialDoc = ext
                    }
                    if (io.bizType === 'onceTrialMaterials') {
                        onceTrialMaterials.push(io)
                        this.typeModel.onceTrialMaterials = ext
                    }
                    if (io.bizType === 'twiceTrialDoc') {
                        twiceTrialDoc.push(io)
                        this.typeModel.twiceTrialDoc = ext
                    }
                    if (io.bizType === 'twiceTrialMaterials') {
                        twiceTrialMaterials.push(io)
                        this.typeModel.twiceTrialMaterials = ext
                    }
                })

                this.onceTrialDocFile = onceTrialDoc
                this.onceTrialMaterialsFile = onceTrialMaterials
                this.twiceTrialDocFile = twiceTrialDoc
                this.twiceTrialMaterialsFile = twiceTrialMaterials
            })
        },
        picChange(fileList, type) {
            console.log(fileList, 999)
            var filePath = fileList[0].name
            var index = filePath.lastIndexOf(".");
            var ext = filePath.substr(index + 1);
            if (type == 'onceTrialDoc') {
                this.typeModel.onceTrialDoc = ext
                this.$refs.typeModel.clearValidate('onceTrialDoc')
                // this.onceTrialDocFile=fileList
            } else if (type == 'onceTrialMaterials') {
                this.$refs.typeModel.clearValidate('onceTrialMaterials')
                this.typeModel.onceTrialMaterials = ext
                // this.onceTrialMaterialsFile=fileList
            } else if (type == 'twiceTrialDoc') {
                this.$refs.typeModel.clearValidate('twiceTrialDoc')
                this.typeModel.twiceTrialDoc = ext
                // this.twiceTrialDocFile=fileList
            } else if (type == 'twiceTrialMaterials') {
                this.$refs.typeModel.clearValidate('twiceTrialMaterials')
                this.typeModel.twiceTrialMaterials = ext
                // this.twiceTrialMaterialsFile=fileList
            }
            this.$forceUpdate()
        },


        handleQuery() {
            this.queryParams.pageNum = 1
            this.getList()
        },
        // 查看
        onInfo(row) {
            this.disabled = true
            this.typeModel = JSON.parse(JSON.stringify(row))
            this.geFileByBizlist()

            this.typeOpen3 = true

        },
        /**  按钮操作 */
        handleAdd(row) {

            this.typeModel = {}
            this.typeModel = JSON.parse(JSON.stringify(row))
            this.geFileByBizlist()
            this.typeOpen = true

        },
        handleAdd2(row, type) {
            this.twotype = type

            this.typeModel = {}
            this.typeModel = JSON.parse(JSON.stringify(row))
            this.geFileByBizlist()
            this.typeOpen2 = true

        },
        close() {
            this.showApprovalModal = false;
            this.showFilesModal = false;
            // this.typeModel= { }
            //  this.$refs.typeModel.resetFields();
        },
        // 删除
        onDelete(row) {
            this.$modal.confirm(this.$t('formValidation.doYouConfirmDeletion')).then(() => {
                skipDel(row.id).then((response) => {
                    if (response.code == 200) {
                        this.$modal.msgSuccess(this.$t('tips.deleteSuccess'))
                        this.getList()
                    }
                })
            })
        },

        // 提交添加
        submitAdd() {
            console.log(this.typeModel, 'typeModel')
            this.$refs.typeModel.validate((valid) => {
                if (valid) {
                    var data = {
                        onceTrialResult: this.typeModel.onceTrialResult,
                        id: this.typeModel.id,
                        onceRemark: this.typeModel.onceRemark,
                        onceTrialDoc: this.typeModel.onceTrialDoc,

                    }
                    // 二次试投
                    // if(this.typeModel.twiceTrial==1){
                    data.twiceTrialResult = this.typeModel.twiceTrialResult
                    // data.twiceTrialMaterials=this.typeModel.twiceTrialMaterials
                    data.twiceTrialDoc = this.typeModel.twiceTrialDoc
                    data.twiceRemark = this.typeModel.twiceRemark
                    // }

                    investmentapproveAPI(data).then(res => {
                        this.$message.success('审批成功')
                        this.getList()
                        this.typeOpen = false
                        this.typeOpen2 = false
                    })
                } else {
                    // this.$modal.msgError(this.$t('formValidation.theBasicInformationIsIncomplete'))

                }
            })
        },

        /**  类型列表 */
        getList() {
            this.loading = true
            var data = {
                ...this.queryParams
            }
            queryProducingTrail(data).then((response) => {

                console.log(response);
                //  if (response.code==200) {
                this.producingTrialItems = response.rows

                this.total = response.total
                this.loading = false

                // }
            }).catch(e => {
                console.log(e);
            })
        },
        // 取消按钮
        resetQuery() {

            this.queryParams = {
                pageNum: 1,
                pageSize: 20
            }
            this.getList()
        },

        /** 关闭操作 */
        handleClose(row) {
            this.$router.go(-1)
        },

    }

}
</script>

<style lang="scss" scoped>
@import './index.scss';
</style>
